package com.shujia.base;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class Code08PutData2 {
    static Connection connection;

    static {
        // 创建连接需要给定连接信息，所以需要给定配置类
        Configuration conf = new Configuration();

        // 由于对HBASE进行操作时，需要连接其Zookeeper 那么需要传入Zookeeper的IP
        conf.set("hbase.zookeeper.quorum", "node1,node2,master");
        // 获取连接对象 通过ConnectionFactory来创建连接对象

        try {
            connection = ConnectionFactory.createConnection(conf);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {

        // api:tb1 中存在两个列族 info1 info2
        // ID name gender age clazz
        // 1500100001,施笑槐,22,女,文科六班
        TableName tableName = TableName.valueOf("api:tb1");
        Table table = connection.getTable(tableName);

//        1500100001,施笑槐,22,女,文科六班
        // 将字符串转成字节数组，最好使用UTF_8形式转换

        Put put = new Put("1500100002".getBytes(StandardCharsets.UTF_8));


        /**
         * 由于Cell是一个抽象类，所以可以通过其子实现类KeyValue来包装数据
         * public KeyValue(final byte [] row, final byte [] family,
         *       final byte [] qualifier, final byte [] value) {
         */
        put.add(
                new KeyValue(
                        "1500100002".getBytes(StandardCharsets.UTF_8),
                        "info1".getBytes(StandardCharsets.UTF_8),
                        "name".getBytes(StandardCharsets.UTF_8),
                        "施笑槐".getBytes(StandardCharsets.UTF_8)
                )
        );

        put.add(new KeyValue(
                "1500100002".getBytes(StandardCharsets.UTF_8),
                "info1".getBytes(StandardCharsets.UTF_8),
                "age".getBytes(StandardCharsets.UTF_8),
                "22".getBytes(StandardCharsets.UTF_8)
        ));

        put.add(new KeyValue(
                "1500100002".getBytes(StandardCharsets.UTF_8),
                "info1".getBytes(StandardCharsets.UTF_8),
                "gender".getBytes(StandardCharsets.UTF_8),
                "女".getBytes(StandardCharsets.UTF_8)
        ));

        put.add(new KeyValue(
                "1500100002".getBytes(StandardCharsets.UTF_8),
                "info2".getBytes(StandardCharsets.UTF_8),
                "clazz".getBytes(StandardCharsets.UTF_8),
                "文科二班".getBytes(StandardCharsets.UTF_8)
        ));

        table.put(put);

        table.close();
        connection.close();
    }
}
